using score_m.dbc;
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace score_m
{
    public partial class teacher_manage : System.Web.UI.Page
    {
        private DatabaseConnect dbc = new DatabaseConnect();

        protected void Page_Load ( object sender, EventArgs e )
        {
            if (!IsPostBack)
            {
                BindTeacherData();
            }
        }

        private void BindTeacherData ( string searchText = "", string searchType = "" )
        {
            string query = "SELECT teacher_id, name, department FROM teacher";
            if (!string.IsNullOrEmpty(searchText))
            {
                query += $" WHERE {searchType} LIKE '%{searchText}%'";
            }

            try
            {
                DataTable dt = dbc.excList(query);
                teacherGridView.DataSource = dt;
                teacherGridView.DataBind();
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '获取数据失败：" + ex.Message + "'})", true);
            }
        }

        protected void searchBtn_Click ( object sender, EventArgs e )
        {
            BindTeacherData(searchInput.Text.Trim(), searchDropList.SelectedValue);
        }

        protected void teacherGridView_RowEditing ( object sender, GridViewEditEventArgs e )
        {
            teacherGridView.EditIndex = e.NewEditIndex;
            BindTeacherData();
        }

        protected void teacherGridView_RowCancelingEdit ( object sender, GridViewCancelEditEventArgs e )
        {
            teacherGridView.EditIndex = -1;
            BindTeacherData();
        }

        protected void teacherGridView_RowUpdating ( object sender, GridViewUpdateEventArgs e )
        {
            string teacherId = teacherGridView.DataKeys[e.RowIndex].Value.ToString();
            string name = ((TextBox)teacherGridView.Rows[e.RowIndex].FindControl("nameEditInput")).Text.Trim();
            string department = ((TextBox)teacherGridView.Rows[e.RowIndex].FindControl("departmentEditInput")).Text.Trim();

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(department))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '请填写完整信息！'})", true);
                return;
            }

            string query = $"UPDATE teacher SET name = '{name}', department = '{department}' WHERE teacher_id = '{teacherId}'";

            try
            {
                int result = dbc.exc(query);
                if (result > 0)
                {
                    teacherGridView.EditIndex = -1;
                    BindTeacherData();
                    ScriptManager.RegisterStartupScript(this, GetType(), "success", "Toast.fire({icon: 'success', title: '更新成功'})", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '更新失败'})", true);
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '更新失败：" + ex.Message + "'})", true);
            }
        }

        protected void teacherGridView_RowDeleting ( object sender, GridViewDeleteEventArgs e )
        {
            string teacherId = teacherGridView.DataKeys[e.RowIndex].Value.ToString();
            string query = $"DELETE FROM teacher WHERE teacher_id = '{teacherId}'";

            try
            {
                int result = dbc.exc(query);
                if (result > 0)
                {
                    BindTeacherData();
                    ScriptManager.RegisterStartupScript(this, GetType(), "success", "Toast.fire({icon: 'success', title: '删除成功'})", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '删除失败'})", true);
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '删除失败：" + ex.Message + "'})", true);
            }
        }

        protected void saveBtn_Click ( object sender, EventArgs e )
        {
            if (string.IsNullOrEmpty(teacherIdInput.Text) || string.IsNullOrEmpty(nameInput.Text) ||
                string.IsNullOrEmpty(departmentInput.Text) || string.IsNullOrEmpty(passwordInput.Text))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '请填写完整信息！'})", true);
                return;
            }

            // 检查工号是否已存在
            DataTable dt = dbc.excList($"SELECT COUNT(*) as count FROM teacher WHERE teacher_id = '{teacherIdInput.Text.Trim()}'");
            if (dt.Rows[0]["count"].ToString() != "0")
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '该工号已存在！'})", true);
                return;
            }

            string query = $"INSERT INTO teacher (teacher_id, name, department, password) VALUES ('{teacherIdInput.Text.Trim()}', '{nameInput.Text.Trim()}', '{departmentInput.Text.Trim()}', '{passwordInput.Text.Trim()}')";

            try
            {
                int result = dbc.exc(query);
                if (result > 0)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "success", "Toast.fire({icon: 'success', title: '添加成功'})", true);
                    // 清空表单
                    teacherIdInput.Text = "";
                    nameInput.Text = "";
                    departmentInput.Text = "";
                    passwordInput.Text = "";
                    // 刷新列表
                    BindTeacherData();
                    // 切换回查询界面
                    ScriptManager.RegisterStartupScript(this, GetType(), "switchToShow", "changeFunc('show');", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '添加失败'})", true);
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "error", "Toast.fire({icon: 'error', title: '添加失败：" + ex.Message + "'})", true);
            }
        }
    }
}
